package com.guli.gulimall.seckill.scheduled;

import com.guli.gulimall.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 秒杀商品的定时上架：
 * 每天晚上3点：上架最近三天要秒杀的商品
 * 当天00：00：00 -23：59：59
 * 明天00：00：00 -23：59：59
 * 后天00：00：00 -23：59：59
 */
@Slf4j
@Service
public class SeckillSkuScheduled {

    @Autowired
    SeckillService seckillService;

    @Autowired
    RedissonClient redissonClient;

    //上架锁
    private final String upload_lock = "seckill:upload:lock";

    //秒伤商品上架定时任务
    @Scheduled(cron = "0/3 * * * * ?")
    public void uploadSeckillSkuLatest3Day() {
        //1.重复上架无需处理
        //分布式锁，同时只能有一台机器上架
        RLock lock = redissonClient.getLock(upload_lock);
        lock.lock(10, TimeUnit.SECONDS);
        try {
            log.info("开始上架秒杀商品------");
            seckillService.uploadSeckillSkuLatest3Day();
            log.info("上架秒杀商品---结束");
        } finally {
            lock.unlock();
        }
    }

}
